package org.learn.controller;

import org.learn.utils.FastdfsClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * FastDFS上传文件控制器
 */
@Controller
public class FdfsClientController {

    private static Logger logger = LoggerFactory.getLogger(FdfsClientController.class);
    @Autowired
    private FastdfsClientUtil fastdfsClientUtil;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file, Model view) {
        try {
            // 获取原文件名
            String origFileName = file.getOriginalFilename();
            logger.info("原始文件名：{}", origFileName);

            // 获取扩展名
            String extName = origFileName.substring(origFileName.lastIndexOf(".") + 1);
            logger.info("原始文件扩展名：{}", extName);

            // 获取文件存储路径
            String[] uriArray = new String[0];

            uriArray = fastdfsClientUtil.uploadFile(file.getBytes(), extName);

            String groupName = uriArray[0];
            String fileId = uriArray[1];

            String uri = groupName + "/" + fileId;
            logger.info("返回的文件存储路径：{}", uri);
            view.addAttribute("uri", uri);


            return "index";
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 下载文件
     *
     * @param filePath
     * @param response
     * @return
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {

        try {


            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            int index = filePath.lastIndexOf("/");
            String fileName = filePath.substring(index + 1);
            //group1/M00/00/00/wKgBa18meFmAHaVYAAW8VIh03qE244.png
            /**
             * 参数格式：
             * groupName: group1
             * fileId: M00/00/00/wKgBa18meFmAHaVYAAW8VIh03qE244.png
             */
            byte[] fileByte = fastdfsClientUtil.downloadFile(group, path);
            InputStream inputStream = new ByteArrayInputStream(fileByte);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            byte[] buff = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
            os.close();
            bis.close();
            logger.info("Download  successfully!");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

    }


    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    @RequestMapping("/deleteFile")
    @ResponseBody
    public String deleteFile(@RequestParam("filePath") String filePath) {
        try {
            /**
             * 参数格式：
             * groupName: group1
             * fileId:M00/00/00/wKgBa18meFmAHaVYAAW8VIh03qE244.png
             */
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);

            int i = fastdfsClientUtil.deleteFile(group, path);
            return (i > 0) ? "删除文件成功" : "删除文件失败";
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return null;
        }

    }

}
